package ccy.ccykills.config;

import ccy.ccykills.playerdata.PlayerData;
import ccy.ccylibrary.config.annotation.FileConfig;
import ccy.ccylibrary.config.annotation.Instance;
import ccy.ccylibrary.data.DataDefault;
import ccy.ccylibrary.data.DefaultData;
import ccy.ccylibrary.data.Mysql;
import ccy.ccylibrary.data.Sqlite;
import ccy.ccylibrary.plugin.annotation.Config;
import ccy.ccylibrary.plugin.annotation.init;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Config
public class CcyConfig {
    @Instance
    public static CcyConfig config;
    public int RankTime;
    public int RankLimit;
    public String RankOut;
    @Mysql
    @Sqlite(
            TableField = {"num INT(16)", "gift VARCHAR(255)"}
    )
    @DataDefault
    public DefaultData data;
    @FileConfig
    public FileConfiguration fileConfiguration;
    public Map<Integer, PlayerInfo> mapRank_total;
    public Map<String, Integer> mapPlayer_total;
    public Map<UUID, KillData> playerNumMap;
    public Map<String, KillGift> killGiftMap;

    public CcyConfig() {
    }

    @init
    public void init() {
        this.mapRank_total = new HashMap();
        this.mapPlayer_total = new HashMap();
        this.playerNumMap = new HashMap();
        this.killGiftMap = new HashMap();

        for(String reward : this.fileConfiguration.getConfigurationSection("reward").getKeys(false)) {
            String name = "reward." + reward + ".";
            this.killGiftMap.put(reward, new KillGift(this.fileConfiguration.getStringList(name + "command"), this.fileConfiguration.getInt(name + "value")));
        }

        this.updateRank();
    }

    public void updateRank() {
        this.playerNumMap.forEach((uid, kill) -> {
            Player player = Bukkit.getPlayer(uid);
            if (player != null && player.isOnline() && kill.isB()) {
                (new PlayerData(player)).setNum(kill.getValue());
            }

        });
        this.data.getSql().connect();
        this.updateData("num", this.mapRank_total, this.mapPlayer_total);
        this.data.getSql().closeConnect();
    }

    private void updateData(String value, Map<Integer, PlayerInfo> rank, Map<String, Integer> player) {
        rank.clear();
        player.clear();
        ResultSet r = this.data.getSortResult(value, this.RankLimit);

        try {
            int i = 0;

            while(r.next()) {
                ++i;
                rank.put(i, new PlayerInfo(r.getString("name"), r.getInt(value)));
                player.put(r.getString("name"), i);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}